package net.hn.hnms.biz.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import net.hn.hnms.biz.project.domain.ConstructionPlan;
import net.hn.hnms.biz.project.domain.ConstructionScheme;
import net.hn.hnms.biz.project.domain.ConstructionTask;
import net.hn.hnms.biz.project.mapper.ConstructionPlanMapper;
import net.hn.hnms.biz.project.mapper.ConstructionSchemeMapper;
import net.hn.hnms.biz.project.mapper.ConstructionTaskMapper;
import net.hn.hnms.biz.project.mapper.ProjectFileMapper;
import net.hn.hnms.biz.project.request.ConstructionPlanReq;
import net.hn.hnms.biz.project.service.IConstructionPlanService;
import net.hn.hnms.biz.project.vo.ConstructionPlanVo;
import net.hn.hnms.biz.project.vo.ProjectInfoVo;
import net.hn.hnms.sys.common.core.domain.R;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.utils.tool.Func;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author 刘昊
 * @date 2024-03-13 16:54
 */
@Service
@Slf4j
public class ConstructionPlanServiceImpl implements IConstructionPlanService {

    @Autowired
    private ConstructionPlanMapper planMapper;

    @Autowired
    private ConstructionTaskMapper taskMapper;

    @Autowired
    private ConstructionSchemeMapper schemeMapper;


    @Autowired
    private ProjectFileMapper projectFileMapper;
    @Override
    public R<Void> insertReq(ConstructionPlanReq req) {
        ConstructionPlan planDO = new ConstructionPlan();
        ConstructionScheme schemeDO = new ConstructionScheme();
        List<ConstructionTask> taskList = req.getConstructionTaskList();
        Calendar startDateCalendar = Calendar.getInstance();
        Calendar endDateCalendar = Calendar.getInstance();
        try {
            BeanUtils.copyProperties(req,planDO);
            log.info("施工计划新增========>");
            planMapper.insert(planDO);
            if (CollectionUtils.isNotEmpty(taskList)) {
                taskList.forEach(task -> {
                    startDateCalendar.setTime(task.getTaskStartDate());
                    endDateCalendar.setTime(task.getTaskEndDate());
                    long diffInMillis = endDateCalendar.getTimeInMillis() - startDateCalendar.getTimeInMillis();
                    int days = (int) (diffInMillis / (1000 * 60 * 60 * 24));
                    task.setConstructionId(planDO.getConstructionId());
                    task.setTaskTime(Integer.toString(days));
                    log.info("施工任务新增========>");
                    taskMapper.insert(task);
                });
            }
            schemeDO.setConstructionId(planDO.getConstructionId());
            schemeDO.setProjectFileName(req.getProjectFileName());
            schemeDO.setProjectFilePath(req.getProjectFilePath());
            log.info("施工方案新增========>");
            schemeMapper.insert(schemeDO);
        }catch (Exception e) {
            log.error("错误信息:{}",e,e);
            return R.fail("新增施工计划失败");
        }
        return R.ok("新增成功");
    }

    @Override
    public R<Void> deleteReq(ConstructionPlanReq req) {
        return null;
    }

    @Override
    public R<Void> updateReq(ConstructionPlanReq req) {

        ConstructionPlan planDO = new ConstructionPlan();
        ConstructionScheme schemeDO = new ConstructionScheme();
        List<ConstructionTask> taskList = req.getConstructionTaskList();
        Calendar startDateCalendar = Calendar.getInstance();
        Calendar endDateCalendar = Calendar.getInstance();
        try {
            BeanUtils.copyProperties(req,planDO);
            planMapper.updateById(planDO);
            if (CollectionUtils.isNotEmpty(taskList)) {
                taskList.forEach(task -> {
                    startDateCalendar.setTime(task.getTaskStartDate());
                    endDateCalendar.setTime(task.getTaskEndDate());
                    long diffInMillis = endDateCalendar.getTimeInMillis() - startDateCalendar.getTimeInMillis();
                    int days = (int) (diffInMillis / (1000 * 60 * 60 * 24));
                    task.setConstructionId(planDO.getConstructionId());
                    task.setTaskTime(Integer.toString(days));
                    taskMapper.updateById(task);
                });
            }
            schemeDO.setConstructionId(planDO.getConstructionId());
            schemeDO.setProjectFileName(req.getProjectFileName());
            schemeDO.setProjectFilePath(req.getProjectFilePath());
            schemeMapper.updateById(schemeDO);
        }catch (Exception e) {
            log.error("错误信息:{}",e,e);
            return R.fail("修改施工计划失败");
        }
        return R.ok("施工计划修改成功");
    }

    @Override
    public R<List<ConstructionPlanVo>> selectList(ConstructionPlanReq req) {
        return null;
    }

    @Override
    public R<Void> deleteList(List<String> idList) {
        QueryWrapper<ConstructionTask> wrapper = new QueryWrapper<>();
        try {
            idList.forEach(item -> {
                String mineCode = planMapper.selectById(item).getMineCode();
                planMapper.deleteById(item);
                wrapper.eq("construction_id",item);
                wrapper.eq("mine_code",mineCode);
                List<String> taskId = taskMapper.selectList(wrapper).stream().map(ConstructionTask::getTaskId).collect(Collectors.toList());
                taskMapper.deleteBatchIds(taskId);
            });

        }catch (Exception e) {
            log.error("错误信息:{}",e,e);
            return R.fail("删除失败");
        }
        return R.ok("删除成功");
    }

    @Override
    public ResponsePage<ConstructionPlanVo> selectPageList(ConstructionPlanReq req, PageQuery pageQuery) {
        //先查询项目信息（项目名称和施工单位）
        List<ProjectInfoVo> projectListByCondition = projectFileMapper.getProjectListByCondition_new(req.getProjectId(), req.getProjectName(), req.getConstructionUnit());
        if (Func.isNotEmpty(projectListByCondition)) {
            //提取projectId列表
            List<String> projectIds = projectListByCondition.stream()
                    .map(ProjectInfoVo::getProjectId)
                    .collect(Collectors.toList());
            req.setProjectIds(projectIds);

            Page<ConstructionPlan> page = planMapper.selectPage(pageQuery.build(), buildQuery(req).orderByDesc(ConstructionPlan::getCreateTime));

            List<ConstructionPlanVo> list = page.getRecords().stream().map(o -> {
                ConstructionPlanVo vo = new ConstructionPlanVo();
                BeanUtil.copyProperties(o, vo);

                // 获取项目名称和施工单位信息
                Optional<ProjectInfoVo> projectInfo = projectListByCondition.stream()
                        .filter(p -> p.getProjectId().equals(o.getProjectId()))
                        .findFirst();

                projectInfo.ifPresent(p -> {
                    vo.setProjectName(p.getProjectName());
                    vo.setConstructionUnit(p.getConstructionUnit());
                });

                return vo;
            }).collect(Collectors.toList());
            return new ResponsePage<>(list, page.getTotal());
        }else {
            return new ResponsePage<>(projectListByCondition, 0);
        }

    }

//    @Override
//    public R<ResponsePage<List<ConstructionPlanVo>>> selectPageList(ConstructionPlanReq req, PageQuery pageQuery) {
//
//        QueryWrapper<ConstructionPlan> wrapper = new QueryWrapper<>();
//        if (StringUtils.isNotBlank(req.getConstructionId())) {
//            wrapper.eq("construction_id",req.getConstructionId());
//        }
//        if (StringUtils.isNotBlank(req.getProjectId())) {
//            wrapper.eq("project_id",req.getProjectId());
//        }
//        if (StringUtils.isNotBlank(req.getProjectName())) {
//            wrapper.eq("project_name",req.getProjectName());
//        }
//        if (StringUtils.isNotBlank(req.getConstructionUnit())) {
//            wrapper.eq("construction_unit",req.getConstructionUnit());
//        }
//        if (StringUtils.isNotBlank(req.getMineCode())) {
//            wrapper.eq("mine_code",req.getMineCode());
//        }
//        if (StringUtils.isNotBlank(req.getPlanName())) {
//            wrapper.eq("plan_name",req.getPlanName());
//        }
//
//        Page<ConstructionPlan> page = planMapper.selectPage(pageQuery.build(),wrapper);
//
//        List<ConstructionPlanVo> resList = page.getRecords().stream()
//                .map(item -> {
//                    ConstructionPlanVo planVo = new ConstructionPlanVo();
//                    BeanUtils.copyProperties(item,planVo);
//                    return planVo;
//                }).collect(Collectors.toList());
//
//        return R.ok("查询完成",new ResponsePage<>(resList, page.getTotal()));
//    }

    private LambdaQueryWrapper<ConstructionPlan> buildQuery(ConstructionPlanReq req){
        return new LambdaQueryWrapper<ConstructionPlan>()
//                .like(StrUtil.isNotBlank(req.getVehicleCode()), ConstructionPlan::getVehicleCode, req.getVehicleCode())
                .in(!org.springframework.util.CollectionUtils.isEmpty(req.getProjectIds()), ConstructionPlan::getProjectId, req.getProjectIds())
                .eq(StrUtil.isNotBlank(req.getProjectId()), ConstructionPlan::getProjectId, req.getProjectId())
                .eq(StrUtil.isNotBlank(req.getMineCode()), ConstructionPlan::getMineCode, req.getMineCode())
                .like(StrUtil.isNotBlank(req.getPlanName()), ConstructionPlan::getPlanName, req.getPlanName());
    }
}
